﻿namespace Amazon.Checkout.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Orchard.ContentManagement;

    public class ContentPartHelper
    {
        private readonly ContentPart contentPart;

        public ContentPartHelper(ContentPart contentPart)
        {
            this.contentPart = contentPart;
        }

        public IEnumerable<string> GetPossibleContentTypeMappings()
        {
            var mappings = new List<string>();

            foreach (var part in this.contentPart.ContentItem.Parts)
            {
                if (part.PartDefinition.Name != this.contentPart.PartDefinition.Name)
                {
                    part.PartDefinition.Fields.ToList().ForEach(f => mappings.Add(f.Name));

                    var type = part.GetType();
                    var partName = part.PartDefinition.Name;

                    foreach (var property in type.GetProperties())
                    {
                        mappings.Add(partName + "." + property.Name);
                    }
                }
            }

            return mappings;
        }

        public string GetValueFromContentItem(string mapping)
        {
            try
            {
                var mappingComponents = mapping.Split('.');

                if (mappingComponents.Length == 1)
                {
                    var fieldName = mappingComponents[0];

                    foreach (var subpart in this.contentPart.ContentItem.Parts)
                    {
                        var a = subpart.Fields.Where(f => f.Name.Equals(fieldName));

                        if (a.Count() > 0)
                        {
                            return a.First().Storage.Get<string>(null);
                        }
                    }
                }

                if (mappingComponents.Length == 2)
                {
                    var partName = mappingComponents[0];
                    var fieldName = mappingComponents[1];

                    foreach (var subpart in this.contentPart.ContentItem.Parts)
                    {
                        if (subpart.PartDefinition.Name == partName)
                        {
                            var propertyInfo = subpart.GetType().GetProperty(fieldName);
                            var value = propertyInfo.GetValue(subpart, new object[0]);

                            if (value == null)
                            {
                                return string.Empty;
                            }

                            return value.ToString();
                        }
                    }
                }
            }
            catch (Exception)
            {
                return "Internal Error";
            }

            return string.Format("Part Not Found: ");
        }
    }
}